<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\api\model\SearchProduct as SearchProductModel;
use app\api\model\OssFile;
use app\common\utils\JsonResponse;
use think\facade\Request;
use think\facade\Db;

class SearchProduct extends AdminController
{
    /**
     * 获取搜索记录列表
     */
    public function list()
    {
        try {
            $page = Request::param('page/d', 1);
            $limit = Request::param('limit/d', 10);
            $startTime = Request::param('start_time', '');
            $endTime = Request::param('end_time', '');

            $query = Db::name('search_product')
                ->alias('s')
                ->join('fa_oss_file f', 'FIND_IN_SET(f.id, s.file_id)', 'LEFT')
                ->join('fa_oss_file sf', 'sf.id = s.search_file_id', 'LEFT')  // 搜索图片
                ->join('fa_user u', 'u.id = s.user_id', 'LEFT')  // 用户信息
                ->whereNull('s.delete_time');

            // 时间范围筛选
            if ($startTime && $endTime) {
                $query->whereBetweenTime('s.create_time', $startTime, $endTime);
            }

            $total = $query->count();
            $list = $query->field([
                    's.id',
                    's.file_id',
                    's.search_file_id',
                    's.product_group',
                    's.create_time',
                    'GROUP_CONCAT(f.file_url) as file_urls',
                    'GROUP_CONCAT(f.file_name) as file_names',
                    'sf.file_url as search_file_url',  // 搜索图片URL
                    'sf.file_name as search_file_name',  // 搜索图片名称
                    'sf.width as search_file_width',  // 搜索图片宽度
                    'sf.height as search_file_height',  // 搜索图片高度
                    'u.id as user_id',  // 用户信息
                    'u.username',
                    // 'u.nickname',
                    'u.avatar'
                ])
                ->group('s.id')
                ->order('s.create_time', 'desc')
                ->page($page, $limit)
                ->select()
                ->each(function($item) {
                    // 处理JSON数据
                    $productGroup = json_decode($item['product_group'], true) ?: [];
                    
                    // 获取所有产品组IDs
                    $groupIds = [];
                    foreach ($productGroup as $group) {
                        if (isset($group['product_ids']) && is_array($group['product_ids'])) {
                            foreach ($group['product_ids'] as $product) {
                                if (isset($product['product_id'])) {
                                    $groupIds[] = $product['product_id'];
                                }
                            }
                        }
                    }
                    
                    // 查询产品组信息
                    if (!empty($groupIds)) {
                        $products = Db::name('t_product_group')
                            ->alias('a')
                            ->leftJoin('sys_file b', 'a.main_img = b.id')
                            ->field('a.id,a.name,a.main_img,b.file_name,b.width,b.height')
                            ->whereIn('a.id', $groupIds)
                            ->select()
                            ->each(function($product) {
                                if ($product['file_name'] && strpos($product['file_name'], 'http') === false) {
                                    $product['file_name'] = 'https://sanyanhu.oss-cn-shenzhen.aliyuncs.com/' . $product['file_name'];
                                }
                                return $product;
                            })
                            ->toArray();
                        
                        // 将产品信息关联到对应的标签组
                        foreach ($productGroup as &$group) {
                            if (isset($group['product_ids']) && is_array($group['product_ids'])) {
                                foreach ($group['product_ids'] as &$product) {
                                    $productId = $product['product_id'];
                                    $productInfo = array_filter($products, function($p) use ($productId) {
                                        return $p['id'] == $productId;
                                    });
                                    $product['product_info'] = !empty($productInfo) ? current($productInfo) : null;
                                }
                            }
                        }
                    }

                    // 更新处理后的数据
                    $item['product_group'] = $productGroup;
                    
                    // 格式化时间
                    $item['create_time'] = $item['create_time'] ? date('Y-m-d H:i:s', $item['create_time']) : '';
                    
                    // 处理多个文件URL
                    $item['file_urls'] = $item['file_urls'] ? explode(',', $item['file_urls']) : [];
                    $item['file_names'] = $item['file_names'] ? explode(',', $item['file_names']) : [];
                    
                    // 处理搜索图片URL
                    if ($item['search_file_url'] && strpos($item['search_file_url'], 'http') === false) {
                        $item['search_file_url'] = env('OSS_DOMAIN') . $item['search_file_url'];
                    }
                    
                    // 处理用户头像
                    if ($item['avatar'] && strpos($item['avatar'], 'http') === false) {
                        $item['avatar'] = env('OSS_DOMAIN') . $item['avatar'];
                    }
                    
                    // 统计信息
                    $item['total_products'] = count($groupIds);
                    $item['label_count'] = count($productGroup);
                    
                    return $item;
                });
            
            return JsonResponse::success([
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'limit' => $limit
            ]);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 获取搜索记录详情
     */
    public function detail()
    {
        try {
            $id = Request::param('id/d', 0);
            
            if ($id <= 0) {
                return JsonResponse::error('ID无效');
            }

            $info = Db::name('search_product')
                ->alias('s')
                ->join('fa_oss_file f', 'f.id = s.file_id', 'LEFT')
                ->field([
                    's.id',
                    's.file_id',
                    's.product_group',
                    's.create_time',
                    'f.file_url',
                    'f.file_name',
                    'f.file_size',
                    'f.mime_type'
                ])
                ->where('s.id', $id)
                ->whereNull('s.delete_time')
                ->find();

            if (!$info) {
                return JsonResponse::error('记录不存在');
            }

            // 处理JSON数据
            $info['product_group'] = json_decode($info['product_group'], true) ?: [];
            // 格式化时间
            $info['create_time'] = $info['create_time'] ? date('Y-m-d H:i:s', $info['create_time']) : '';
            // 格式化文件大小
            $info['file_size'] = format_bytes($info['file_size']);

            return JsonResponse::success($info);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 删除搜索记录
     */
    public function delete()
    {
        try {
            $id = Request::param('id/d', 0);
            
            if ($id <= 0) {
                return JsonResponse::error('ID无效');
            }

            $result = Db::name('search_product')
                ->where('id', $id)
                ->update(['delete_time' => time()]);

            return $result !== false 
                ? JsonResponse::success([], '删除成功') 
                : JsonResponse::error('删除失败');
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 批量删除搜索记录
     */
    public function batchDelete()
    {
        try {
            $ids = Request::param('ids/a', []);
            
            if (empty($ids)) {
                return JsonResponse::error('请选择要删除的记录');
            }

            $result = Db::name('search_product')
                ->whereIn('id', $ids)
                ->update(['delete_time' => time()]);

            return $result !== false 
                ? JsonResponse::success([], '批量删除成功') 
                : JsonResponse::error('批量删除失败');
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
} 